package com.zhangxiaofanfan.hotcode.first;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 *
 * @date 2024-07-13 03:14:13
 * @author zhangxiaofanfan
 */
public class HotCode086 {
    public static void main(String[] args) {
        HotCode086 hotCode = new HotCode086();
        String s = "catsandog";
        List<String> wordDict = new ArrayList<>(
                List.of("cats","dog","sand","and","cat")
        );
        System.out.println(hotCode.wordBreak(s, wordDict));
    }

    public boolean wordBreak(String s, List<String> wordDict) {
        if (s == null || s.isEmpty()) {
            return true;
        }
        wordDict.sort(Comparator.comparingInt(String::length));
        if (s.length() < wordDict.getFirst().length()) {
            return false;
        }
        boolean[] dp = new boolean[s.length() + 1];
        dp[0] = true;
        for (int i = wordDict.getFirst().length(), curIndex = 0; i <= s.length(); i++) {
            for (curIndex = 0; curIndex < wordDict.size(); curIndex++) {
                int before = i - wordDict.get(curIndex).length();
                if (before >= 0 && dp[before] && s.substring(before, i).endsWith(wordDict.get(curIndex))) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[s.length()];
    }

}